package org.libermundi.theorcs.core.tapestry.util;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import org.apache.tapestry5.OptionGroupModel;
import org.apache.tapestry5.OptionModel;
import org.apache.tapestry5.internal.OptionGroupModelImpl;
import org.apache.tapestry5.util.AbstractSelectModel;
import org.libermundi.theorcs.core.model.base.Identifiable;
import org.libermundi.theorcs.core.model.base.Labelable;

import com.google.common.collect.Lists;

/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class GenericSelectModel<T extends Identifiable<I>, I extends Serializable> extends AbstractSelectModel {
	private List<OptionGroupModel> _optionsGroups = Lists.newArrayList();
	
	private List<OptionModel> _options = Lists.newArrayList();
	
	public GenericSelectModel(List<T> values) {
		this(values,true);
	}
	
	public GenericSelectModel(List<T> values, boolean showGroups) {
		for (Iterator<T> iterator = values.iterator(); iterator.hasNext();) {
			T item = iterator.next();
			OptionModel option = getOption(item);
			if(item instanceof Groupable && showGroups) {
				String grpLabel = ((Groupable) item).printGroupLabel();
				getGroup(grpLabel).getOptions().add(option);
			} else {
				_options.add(option);
			}
		}
	}
	
	@Override
	public List<OptionGroupModel> getOptionGroups() {
		return _optionsGroups;
	}

	@Override
	public List<OptionModel> getOptions() {
		return _options;
	}

	/**
	 * @param item
	 * @return
	 */
	private OptionModel getOption(T item) {
		if(item instanceof Labelable) {
			return new GenericOptionModel<>(((Labelable) item).printLabel(), item);
		}
		return new GenericOptionModel<>(item.toString(), item);
	}

	/**
	 * 
	 * @param label
	 * @return
	 */
	private OptionGroupModel getGroup(String label) {
		for (OptionGroupModel group : _optionsGroups) {
			if(group.getLabel().equals(label)){
				return group;
			}
		}
		List<OptionModel> options = Lists.newArrayList();
		//The Group does not yet exists
		OptionGroupModel group = new OptionGroupModelImpl(label, Boolean.FALSE, options);
		
		_optionsGroups.add(group);
		
		return group;
	}
}
